// @test([5,3,6,2,4,null,null,1], 1)=2
// @algorithm @lc id=100178 lang=javascript
// @title successor-lcci
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @return {TreeNode}
 */
var inorderSuccessor = function (root, p) {
  const inorder = (node) => {
    if (node === null) return;
    inorder(node.left);
    // 当前一个结点和p相同，当前结点就是后继结点
    if (pre === p) {
      ans = node;
    }
    pre = node;
    inorder(node.right);
    return;
  };
  let pre = null;
  let ans = null;
  inorder(root);
  return ans;
};
